'use strict'
const router=require('koa-router')();
const fs=require('fs');
function getrouterfiles(path){
    let tmppath=path||__dirname;
    let files=fs.readdirSync(tmppath);
    let routerfiles=files.filter(item=>{
        //后缀为.js排除index.js
        return item.endsWith('.js')&&item!=='index.js';
    })
    return routerfiles
}
//注册路由
function registryroute(router,routerfiles){
    routerfiles.forEach(item=>{
        let tmppath=__dirname+'/'+item;
        let obj=require(tmppath);
        for(let key in obj){
            let tmparr=key.split(' ');
            let rmethod=tmparr[0];
            let rpath=tmparr[1];
            let rfunction=obj[key];
            if(rmethod==='get'){
                router.get(rpath,rfunction);
            }else if(rmethod=='post'){
                router.post(rpath,rfunction);
            }else if(rmethod==='put'){
                router.put(rpath,rfunction);
            }else if(rmethod==='delete'){
                router.delete(rpath,rfunction);
            }else{
                console.log('失败');
            }
        }
    });
    return router.routes();
}
module.exports=function(){
    let routerfiles=getrouterfiles();
    let fn=registryroute(router,routerfiles);
    return fn;
}
